package com.iotimc.networklibrary.core;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.WindowManager;

import com.iotimc.networklibrary.entity.BaseEntity;

import io.reactivex.observers.DisposableObserver;


/**
 * @param <T> 根据传入的对象决定参数类型
 * @author david
 */
public abstract class BaseObserver<T> extends DisposableObserver<BaseEntity<T>> {

    private static final String TAG = "BaseObserver";
    private Context mContext;
    private boolean isNeedShowDialog;
    ProgressDialog progressDialog;

    protected BaseObserver(Context context, boolean isNeedShowDialog) {
        this.mContext = context.getApplicationContext();
        this.isNeedShowDialog = isNeedShowDialog;
        if (isNeedShowDialog) {
            progressDialog = new ProgressDialog(context);
            progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isNeedShowDialog) {
            progressDialog.show();
        }
    }

    @Override
    public void onNext(BaseEntity<T> value) {
        if (value.isSuccess()) {
            T t = value.getResult();
            onHandleSuccess(t);
        } else {
            onHandleError(value.getMessage());
        }
    }

    @Override
    public void onError(Throwable e) {
        Log.e(TAG, "error:" + e.toString());
        onHandleError(e.getMessage());
        if (isNeedShowDialog) {
            progressDialog.dismiss();

        }
    }

    @Override
    public void onComplete() {
        Log.d(TAG, "onComplete");
        if (isNeedShowDialog) {
            progressDialog.dismiss();

        }
    }

    /**
     * 返回成功
     *
     * @param t javabean对象
     */
    protected abstract void onHandleSuccess(T t);

    /**
     * 返回失败
     *
     * @param msg 失败信息
     */
    protected abstract void onHandleError(String msg);
}
